var http = require("../../utils/http.js");
var config = require("../../utils/config.js");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    records:[],
    shareShow:false,
    wxCodeShow:false,
    shareProdId:0,
    shareProdName: "",
    sharePic: "",
    shareWxCode:"",//分享商品微信二维码
    loadingMsg:"正在加载..",
    emptyMsg:"",
    totalPage:1,
    pageNum:1,
    prodName:"",//搜索的名称
    orderBy: 1,//排序(0升序 1降序) 默认1
    sort: 1 //排序(0 佣金排序 1时间排序 2销量排序 3价格排序) 默认1
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.showLoading();
    this.loadPageData(1);
  },

  //加载分页数据
  loadPageData: function (pageNum) {
    var ths = this;
    http.request({
      url: "/p/distribution/prod/page",
      method: "GET",
      data: {
        shopId: 1,
        current: pageNum,
        orderBy: this.data.orderBy,
        prodName: this.data.prodName,
        size: 20,
        sort: this.data.sort,
      },
      callBack: (res) => {
        wx.hideLoading();
        var records = [];
        if (res.current == 1) {
          records = res.records;
        } else {
          // records = this.data.records;
          // Array.prototype.push.apply(records, res.records);
          records = this.data.records.concat(res.records);
        }
        var loadingMsg = this.data.loadingMsg;
        if (pageNum == res.pages) {
          loadingMsg = "没有更多了~";
        }
        console.log(res)
        ths.setData({
          records: records,
          totalPage: res.pages,
          pageNum: pageNum,
          loadingMsg: loadingMsg,
          emptyMsg: "没有找到推广商品哦~"
        });
      }
    });
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.showLoading();
    this.loadPageData(1);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.pageNum < this.data.totalPage) {
      this.loadPageData(this.data.pageNum + 1);
    }
  },

  /** 
   * 点击导航菜单
   */
  onTabTouch:function(e){
    var sort = e.currentTarget.dataset.sort;
    if(sort==this.data.sort){
      this.setData({
        orderBy:this.data.orderBy==0?1:0
      });
      wx.showLoading();
      this.loadPageData(1);
    }else{
      this.setData({
        sort: sort,
        orderBy:1
      });
      wx.showLoading();
      this.loadPageData(1);
    }
  },

  /**
   * 名称输入
   */
  onProdNameInput:function(e){
    this.setData({
      prodName:e.detail.value
    });
  },

  /**
   * 搜索
   */
  onProdNameSearch:function(){
    wx.showLoading();
    this.loadPageData(1);
  },

  /**
   * 显示分享弹窗
   */
  onShowShare: function (e) {
    var prodId = e.currentTarget.dataset.prodid;
    var prodName = e.currentTarget.dataset.prodname;
    var pic = e.currentTarget.dataset.pic;
    var shareType = e.currentTarget.dataset.type;
    console.log(e)
    this.setData({
      shareShow: true,
      shareProdId:prodId,
      shareProdName: prodName,
      sharePic: pic,
      shareType: shareType
    });

    //从缓存获取分销员卡号，如果没有则去接口获取，以备转发时使用
    var cardno = wx.getStorageSync("distCardNo");
    if (!cardno) {
      http.request({
        url: "/p/distribution/user/distributionUserInfo",
        method: "GET",
        data: {
          shopId: 1,
        },
        callBack: (res) => {
          wx.setStorageSync("distCardNo", res.cardNo);
        }
      })
    }
  },

  /**
   * 关闭分享弹窗
   */
  closeEarn: function () {
    this.setData({
      shareShow: false
    })
  },

  /**
   * 用户点击转发
   */
  onShareAppMessage:function(res){
    if (res.from === 'button') {
      var cardno = wx.getStorageSync("distCardNo");
      return {
        title: this.data.shareProdName,
        path: '/pages/prod/prod?prodid=' + this.data.shareProdId + '&cardno=' + cardno + '&type=' + this.data.shareType,
        imageUrl: this.data.sharePic
      }
    }
  },

  /**
   * 生成小程序二维码
   */
  genWeixinCode() {
    wx.showLoading({
      mask: true
    })
    var cardNo = wx.getStorageSync("distCardNo");
    var content = JSON.stringify({
      shareProdId: this.data.shareProdId,
      cardNo: cardNo,
    })
    http.request({
      url: "/qrcodeTicket/miniQrCode",
      method: "GET",
      responseType: 'arraybuffer',
      data: {
        content: content,
        type: 2
      },
      callBack: (res) => {
        this.setData({
          wxCodeShow: true,
          shareShow: false,
          shareWxCode: "data:image/jpg;base64," + wx.arrayBufferToBase64(res)
        });
        wx.hideLoading();
      }
    })
  },

  /**
   * 关闭二维码弹窗
   */
  closeCodePopup(){
    this.setData({
      wxCodeShow: false
    });
  },

  /**
   * 保存图片至相册
   */
  downloadImg() {
    var ths = this
    var imgSrc = this.data.shareWxCode.slice(22); //base64编码
    var save = wx.getFileSystemManager();
    save.writeFile({
      filePath: wx.env.USER_DATA_PATH + '/分享商品-' + this.data.shareProdName + '.png',
      data: imgSrc,
      encoding: 'base64',
      success: res => {
        wx.saveImageToPhotosAlbum({
          filePath: wx.env.USER_DATA_PATH + '/分享商品-' + this.data.shareProdName + '.png',
          success: function (res) {
            wx.showToast({
              title: '保存成功',
            })
            ths.setData({
              wxCodeShow: false
            })
          },
          fail: function (err) {
            wx.showModal({
              title: '提示',
              content: '保存图片需要授予存储权限',
              success: modalRes => {
                if (modalRes.confirm) {
                  wx.openSetting({
                    success(settingdata) {
                      if (settingdata.authSetting['scope.writePhotosAlbum']) {
                        console.log('用户权限成功')
                      } else {
                        console.log('用户取消权限')
                      }
                    }
                  })
                }
              }
            })
          }
        })
        console.log(res)
      },
      fail: err => {
        console.log(err)
      }
    })
  }
})